<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { ExchangeRecordItem, ExchangeRecordParams } from '@/types/exchangeRecord'
import { getExchangeRecordAPI, updateExchangeRecordStatusAPI } from '@/services/points'
import PageSkeleton from './components/PageSkeleton.vue'
import { useMemberStore } from '@/stores'

// 会员信息
const memberStore = useMemberStore()

const isTeacher = memberStore.profile?.role === 'teacher'

// 兑换记录列表数据
const recordList = ref<ExchangeRecordItem[]>([])
// 分页参数
const pageParams = ref<ExchangeRecordParams>({
  pageNum: 1,
  pageSize: 10,
  status: '-1', // 默认显示全部状态
})
// 是否有更多数据
const hasMore = ref(true)
// 是否下拉刷新中
const isTriggered = ref(false)
// 数据是否加载完成
const isFinish = ref(false)
// 当前选中的状态筛选
const activeStatus = ref('-1')
// 加载状态映射(用于防止重复点击)
const loadingStatus = ref<Record<string, boolean>>({})

// 获取兑换记录数据
const getExchangeRecordData = async () => {
  const res = await getExchangeRecordAPI(pageParams.value)
  // 添加数据
  if (pageParams.value.pageNum === 1) {
    recordList.value = res.data.rows
  } else {
    recordList.value = [...recordList.value, ...res.data.rows]
  }
  // 判断是否还有更多数据
  hasMore.value = res.data.rows.length === pageParams.value.pageSize
  // 更新页码
  pageParams.value.pageNum = (pageParams.value.pageNum || 1) + 1
}

// 页面加载
onMounted(async () => {
  await getExchangeRecordData()
  isFinish.value = true
})

// 下拉刷新
const onRefresherrefresh = async () => {
  isTriggered.value = true
  pageParams.value.pageNum = 1
  await getExchangeRecordData()
  isTriggered.value = false
}

// 上拉加载更多
const handleLoadMore = async () => {
  if (hasMore.value) {
    await getExchangeRecordData()
  }
}

// 切换状态筛选
const changeStatus = async (status: string) => {
  if (activeStatus.value === status) return
  activeStatus.value = status
  pageParams.value.status = status
  pageParams.value.pageNum = 1
  isFinish.value = false
  await getExchangeRecordData()
  isFinish.value = true
}

// 更新兑换记录状态
const updateRecordStatus = async (recordId: number, newStatus: string) => {
  // 设置加载状态
  loadingStatus.value[recordId] = true
  try {
    const res = await updateExchangeRecordStatusAPI({ id: recordId, status: newStatus })
    if (res.code === 200) {
      uni.showToast({
        title: newStatus === '1' ? '已标记为已兑换' : '已拒绝兑换',
        icon: 'success',
        duration: 2000,
      })
      // 刷新数据
      pageParams.value.pageNum = 1
      await getExchangeRecordData()
    } else {
      uni.showToast({
        title: '操作失败，请重试',
        icon: 'none',
        duration: 2000,
      })
    }
  } catch (error) {
    uni.showToast({
      title: '网络异常，请重试',
      icon: 'none',
      duration: 2000,
    })
    console.error('更新兑换记录状态失败:', error)
  } finally {
    // 重置加载状态
    loadingStatus.value[recordId] = false
  }
}

// 状态文本映射
const statusTextMap = {
  '-1': '全部',
  '0': '待审核',
  '1': '已通过',
  '2': '已拒绝',
}

// 状态颜色映射
const statusColorMap = {
  '0': '#FF9800', // 橙色
  '1': '#4CAF50', // 绿色
  '2': '#F44336', // 红色
}
</script>

<template>
  <view class="viewport" v-if="isFinish">
    <!-- 状态筛选栏 -->
    <view class="status-filter">
      <view
        v-for="status in ['-1', '0', '1', '2']"
        :key="status"
        class="status-item"
        :class="{ active: activeStatus === status }"
        @click="changeStatus(status)"
      >
        {{ statusTextMap[status as keyof typeof statusTextMap] }}
      </view>
    </view>

    <!-- 兑换记录列表 -->
    <scroll-view
      class="record-list"
      :enable-back-to-top="true"
      :refresher-enabled="true"
      @refresherrefresh="onRefresherrefresh"
      :refresher-triggered="isTriggered"
      @scrolltolower="handleLoadMore"
      :scroll-y="true"
    >
      <!-- 列表项 -->
      <view v-if="recordList.length > 0" class="record-items">
        <view v-for="record in recordList" :key="record.id" class="record-item">
          <view class="record-info">
            <image class="gift-image" :src="record.giftPicture" mode="aspectFill"></image>
            <view class="gift-info">
              <view class="gift-name">{{ record.giftName }}</view>
              <view v-if="isTeacher" class="receiver-name">
                <text>兑换人：{{ record.receiverName }}</text>
              </view>
              <view class="exchange-time">{{ record.exchangeTime }}</view>
              <view class="points">
                <image class="point-image" src="@/static/images/points.png"></image>
                <text>{{ record.points }}</text>
              </view>
            </view>
          </view>
          <!-- 状态显示或操作按钮 -->
          <template v-if="isTeacher && record.status == '0'">
            <view class="action-buttons">
              <button
                class="btn accept-btn"
                :loading="loadingStatus[record.id]"
                @click="updateRecordStatus(record.id, '1')"
              >
                已兑换
              </button>
              <button
                class="btn reject-btn"
                :loading="loadingStatus[record.id]"
                @click="updateRecordStatus(record.id, '2')"
              >
                已拒绝
              </button>
            </view>
          </template>
          <template v-else>
            <view
              class="record-status"
              :style="{ backgroundColor: statusColorMap[record.status as keyof typeof statusColorMap] }"
            >
              {{ statusTextMap[record.status as keyof typeof statusTextMap] }}
            </view>
          </template>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else class="empty-state">
        <image src="@/static/images/empty.png" mode="aspectFit"></image>
        <text>暂无兑换记录</text>
      </view>
    </scroll-view>
  </view>
  <PageSkeleton v-else />
</template>

<style lang="scss">
@import './styles/points.scss';

.viewport {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
}
.receiver-name {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  // color: #666;
  margin: 10rpx 0;
  // background-color: #f5f5f5;
  border-radius: 8rpx;
}
/* 状态筛选栏 */
.status-filter {
  display: flex;
  padding: 16rpx 0;
  background-color: #fff;
  border-bottom: 1rpx solid #e3e4e7;
  overflow-x: auto;
  white-space: nowrap;
  .status-item {
    padding: 10rpx 30rpx;
    margin: 0 10rpx;
    font-size: 26rpx;
    color: #595c63;
    border-radius: 30rpx;
    &.active {
      background-color: #27ba9b;
      color: #fff;
    }
  }
}

/* 兑换记录列表 */
.record-list {
  flex: 1;
  padding: 20rpx;
  .record-items {
    .record-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx;
      margin-bottom: 20rpx;
      background-color: #fff;
      border-radius: 16rpx;
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
      .record-info {
        display: flex;
        flex: 1;
        .gift-image {
          width: 140rpx;
          height: 140rpx;
          border-radius: 12rpx;
          margin-right: 20rpx;
        }
        .gift-info {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          flex: 1;
          .gift-name {
            font-size: 30rpx;
            color: #333;
            max-width: 300rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .exchange-time {
            font-size: 24rpx;
            color: #999;
          }
          .points {
            display: flex;
            align-items: center;
            font-size: 26rpx;
            color: #cf4444;
            .point-image {
              width: 26rpx;
              height: 26rpx;
              margin-right: 6rpx;
            }
          }
        }
      }
      .record-status {
        padding: 6rpx 16rpx;
        font-size: 24rpx;
        color: #fff;
        border-radius: 18rpx;
      }
      .action-buttons {
        display: flex;
        flex-direction: column;
        gap: 10rpx;
      }
      .btn {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 8rpx 16rpx;
        border-radius: 8rpx;
        font-size: 24rpx;
        color: #fff;
        border: none;
        min-width: 120rpx;
        &.accept-btn {
          background-color: #4caf50;
        }
        &.reject-btn {
          background-color: #f44336;
        }
        &:active {
          opacity: 0.8;
          transform: scale(0.95);
        }
      }
    }
  }
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 400rpx;
    image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 20rpx;
      opacity: 0.5;
    }
    text {
      font-size: 28rpx;
      color: #999;
    }
  }
}

/* 适配不同屏幕尺寸 */
@media screen and (min-width: 768px) {
  .record-item {
    max-width: 600rpx;
    margin-left: auto;
    margin-right: auto;
  }
}

@media screen and (max-width: 320px) {
  .status-item {
    padding: 8rpx 20rpx;
    font-size: 24rpx;
  }
  .gift-name {
    font-size: 26rpx !important;
  }
  .exchange-time {
    font-size: 22rpx !important;
  }
  .points {
    font-size: 24rpx !important;
  }
  .record-status {
    padding: 4rpx 12rpx;
    font-size: 22rpx;
  }
  .btn {
    padding: 6rpx 12rpx;
    font-size: 22rpx;
    min-width: 100rpx;
  }
}
</style>
